package com.luo.d3s.anti.mvc.ec.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import com.luo.d3s.core.util.JsonUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;

/**
 * Spring Cache配置
 *
 * @author luohq
 * @date 2023-01-06 8:35
 */
@Configuration
@EnableCaching
public class SpringCacheConfig {
    /**
     * 默认缓存超期时长
     */
    @Value("${cache.ttl:3600}")
    private Long cacheTtlSeconds;

    /**
     * Redis Cache配置
     */
    @Bean
    public RedisCacheConfiguration cacheConfiguration() {
        return RedisCacheConfiguration.defaultCacheConfig()
                //缓存时长（默认1小时）
                .entryTtl(Duration.ofSeconds(this.cacheTtlSeconds))
                //设置Value序列化器为Jackson（Key默认String序列化,Value默认Java序列化）
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(redisJacksonSerializer()));
    }

    /**
     * RedisTemplate配置
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        //设置value的序列化方式json
        redisTemplate.setValueSerializer(redisJacksonSerializer());
        //设置key序列化方式String
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        //设置hash key序列化方式String
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        //设置hash value序列化json
        redisTemplate.setHashValueSerializer(redisJacksonSerializer());
        //设置支持事务（默认关闭，若开启后在@Transactional方法中incre等无法获取返回值）
        redisTemplate.setEnableTransactionSupport(false);
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }

    /**
     * Redis序列化器配置
     */
    @Bean
    public RedisSerializer<Object> redisJacksonSerializer() {
        //创建JSON序列化器
        ObjectMapper objectMapper = JsonUtils.standardObjectMapper();
        //设置可见性
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        //必须设置，否则无法将JSON转化为对象，会转化成Map类型
        objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL);
        return new GenericJackson2JsonRedisSerializer(objectMapper);
    }
}
